# oxyxy-bot : Mathematical Amanuensis

from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document

import logging
logger = logging.getLogger('oxyxy-bot')
logger.setLevel(logging.DEBUG) 

from parser import *

from string import *

def OnParticipantsChanged(properties, context):
  """Invoked when any participants have been added/removed."""
  pass

def OnRobotAdded(properties, context):
  """Invoked when the robot has been added."""
  root_wavelet = context.GetRootWavelet()
  root_wavelet.CreateBlip().GetDocument().SetText("Hi, oxyxy here. Thanks for adding me to this wave. I'm here to help you do maths.")

def OnBlipSubmitted(properties, context):
    blip = context.GetBlipById(properties['blipId'])
    contents = blip.GetDocument().GetText()
    
    if( blip.GetCreator() != 'oxyxy-bot@appspot.com'):
        
        # Do something with the contents of the blip
        r = document.Range(0,0)
        r.start = 0
        currentBlipText = blip.GetDocument().GetText()
        r.end = r.start + len(currentBlipText)
        adaptedBlipText = replace(currentBlipText, r"$", r"$$")
        if(currentBlipText == adaptedBlipText):
            return
        blip.GetDocument().SetTextInRange(r, adaptedBlipText) # remove markup
        
        # Use SymPy to Process the orginal blip contents
        # Differentiate $\cos(x)$ with respect to $x$ 
        sympyResult = MathtexParser().parse(currentBlipText)
        
        # Output the result of using SymPy
        currentWavelet = context.GetWaveletById( blip.GetWaveletId() )
        newBlip = currentWavelet.CreateBlip()
        newBlip.GetDocument().SetText(r'$' + sympyResult[0]+ r'$')
        newBlip.Submit()
        
        #insert the gadget
        #gadget = document.Gadget(___) # setup gadget instance
        #blip.GetDocument().InsertElement(r.start, gadget) # insert gadget
        #delta = {'varName' : value} # set state 
        #blip.GetDocument().GadgetSubmitDelta(gadget, delta) # submit the delta

if __name__ == '__main__':
  current_version = 1
  #logger.debug('text: %s' % "running version " + current_version) 
  myRobot = robot.Robot('oxyxy-bot', 
      image_url='http://oxyxy-bot.appspot.com/assets/icon.PNG',
      version=current_version,
      profile_url='http://oxyxy-bot.appspot.com/')
  myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
  myRobot.Run(debug=True)
